package com.sx.mongodb.controller;

import com.alibaba.fastjson.JSON;
import com.sx.mongodb.dao.StudentDaoTypeDao;
import com.sx.mongodb.model.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class MongoDbController {

    @Autowired
    private StudentDaoTypeDao studentDaoTypeDao;

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("/get")
    public Object findStudent(){

        String studentName="Godfery0";
        Query query=Query.query(Criteria.where("studentName").is(studentName).and("studentScore").gte(97))
                .with(Sort.by(Sort.Order.desc("studentScore")));
        List<Student> studentList = mongoTemplate.find(query,Student.class);
        log.info("studentList-->"+JSON.toJSONString(studentList));
        Student student = studentDaoTypeDao.findStudentByStudentName(studentName);
        return student;
    }

    @RequestMapping("/all")
    public Object findAll(){
        String studentName="test";
        Sort sort = Sort.sort(Student.class);
        List<Student> studentList = studentDaoTypeDao.findAll(sort);
        return studentList;
    }


    @RequestMapping("/update")
    public Object updateStudent(){
        String studentName="Godfery0";
        Student student = studentDaoTypeDao.findStudentByStudentName(studentName);
        student.setStudentName("test");
        studentDaoTypeDao.save(student);
        return student;
    }

    @RequestMapping("")
    public Object addStudent(){
        for (Integer count = 0; count < 5; count++) {
            Student student = new Student()
                    .setStudentId("student_"+count) //如果自己不去设置id则系统会分配给一个id
                    .setStudentName("Godfery"+count)
                    .setStudentAge(count)
                    .setStudentScore(98.5-count)
                    .setStudentBirthday(new Date());
            studentDaoTypeDao.save(student);
        }
        return "success";
    }
}
